<?php

function user_entity_from_memcache($userid, $result = NULL) {
    $key = "user_entity_" . $userid;
    static $memcache = FALSE;
    if (!$memcache) {
        global $GS_CONFIG;
        $host = $GS_CONFIG->memcache;
        $port = 11211;
        $memcache = new Memcache();
        $memcache->addServer($host, $port);
        $stats = @$memcache->getExtendedStats();
        $available = (bool) $stats["$host:$port"];
        if (!( $available && @$memcache->connect($host, $port))) {
            return $result;
        }
    }

    if (empty($result)) {
        $cached_result = $memcache->get($key);
//        echo "hit cache OK";
        return $cached_result;
    } else {
        $memcache->set($key, $result, false, 360);
//        echo "set cache OK";
        return $result;
    }
}

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
// Get variables
//$is_debug = get_input('debug', FALSE);
$id = get_input('user_id');
$brief = get_input('brief');
$client_id = get_input('client_id');

if ($id == 'me') {
    $userid = get_loggedin_userid();
    if (intval($userid) <= 0) {
        echo json_encode(export_result(400, "Your session is expired, please try login again!"));
        exit;
    }
} else {
    $userid = $id;
}

$userEntity = get_entity($userid);

/*
$userEntity = user_entity_from_memcache($userid);
if (empty($userEntity)) {
    $userEntity = get_entity($userid);
    user_entity_from_memcache($userid, $userEntity);
}
*/

if ($userEntity) {
    $user = userToArray($userEntity, $client_id, $brief);
    if ($id == 'me') {
        $user['email'] = $userEntity->email;
    }
    $result = export_result(200, $user);
} else {
    $result = export_result(400, "Cannot find user id #$userid#");
}

echo json_encode($result);
?>